<template>
  <div class="logs-viewer">
    <!-- 日志查看器 -->
    <el-card class="logs-card">
      <template #header>
        <div class="card-header">
          <el-icon><Document /></el-icon>
          <span>系统日志</span>
          <div class="header-actions">
            <el-button-group>
              <el-button 
                :type="realtimeMode ? 'primary' : ''"
                @click="toggleRealtime"
                :loading="connecting"
              >
                <el-icon><VideoPlay v-if="!realtimeMode" /><VideoPause v-else /></el-icon>
                {{ realtimeMode ? '停止实时' : '实时日志' }}
              </el-button>
              <el-button @click="refreshLogs" :loading="loading">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <el-button @click="clearLogs" type="danger">
                <el-icon><Delete /></el-icon>
                清空
              </el-button>
            </el-button-group>
            <el-button @click="downloadLogs">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </div>
        </div>
      </template>

      <!-- 日志过滤器 -->
      <div class="log-filters">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="6">
            <el-select 
              v-model="filterLevel" 
              placeholder="日志级别"
              clearable
              @change="applyFilters"
              style="width: 100%"
            >
              <el-option label="全部级别" value="" />
              <el-option label="DEBUG" value="debug">
                <el-tag size="small" type="info">DEBUG</el-tag>
              </el-option>
              <el-option label="INFO" value="info">
                <el-tag size="small" type="success">INFO</el-tag>
              </el-option>
              <el-option label="WARN" value="warn">
                <el-tag size="small" type="warning">WARN</el-tag>
              </el-option>
              <el-option label="ERROR" value="error">
                <el-tag size="small" type="danger">ERROR</el-tag>
              </el-option>
            </el-select>
          </el-col>

          <el-col :xs="24" :sm="6">
            <el-select 
              v-model="filterSource" 
              placeholder="日志来源"
              clearable
              @change="applyFilters"
              style="width: 100%"
            >
              <el-option label="全部来源" value="" />
              <el-option label="系统" value="system" />
              <el-option label="MQTT" value="mqtt" />
              <el-option label="设备采集" value="device" />
              <el-option label="Web服务" value="web" />
              <el-option label="协议处理" value="protocol" />
            </el-select>
          </el-col>

          <el-col :xs="24" :sm="8">
            <el-input 
              v-model="searchKeyword" 
              placeholder="搜索日志内容..."
              clearable
              @input="applyFilters"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>

          <el-col :xs="24" :sm="4">
            <el-input-number
              v-model="maxLines"
              :min="100"
              :max="10000"
              :step="100"
              style="width: 100%"
              placeholder="显示行数"
              @change="applyFilters"
            />
          </el-col>
        </el-row>

        <!-- 时间范围选择 -->
        <el-row :gutter="20" class="mt-3">
          <el-col :xs="24" :sm="12">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="applyFilters"
              style="width: 100%"
            />
          </el-col>
          
          <el-col :xs="24" :sm="6">
            <el-switch 
              v-model="autoScroll"
              active-text="自动滚动"
              inactive-text="锁定滚动"
              @change="handleAutoScrollChange"
            />
          </el-col>

          <el-col :xs="24" :sm="6">
            <div class="log-stats">
              总计: {{ totalLogs }} 条 | 已显示: {{ displayedLogs }} 条
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 日志内容 -->
      <div class="log-content">
        <div 
          ref="logContainer"
          class="log-container"
          @scroll="handleScroll"
        >
          <div 
            v-for="(log, index) in filteredLogs" 
            :key="`${log.timestamp}-${index}`"
            :class="getLogClass(log)"
            class="log-entry"
          >
            <div class="log-time">
              {{ formatLogTime(log.timestamp) }}
            </div>
            <div class="log-level">
              <el-tag :type="getLevelTagType(log.level)" size="small">
                {{ log.level.toUpperCase() }}
              </el-tag>
            </div>
            <div class="log-source" v-if="log.source">
              <el-tag type="info" size="small" plain>
                {{ log.source }}
              </el-tag>
            </div>
            <div class="log-message">
              <span v-html="highlightMessage(log.message)"></span>
            </div>
          </div>

          <!-- 加载更多 -->
          <div v-if="hasMoreLogs && !realtimeMode" class="load-more">
            <el-button @click="loadMoreLogs" :loading="loadingMore" type="text">
              加载更多日志
            </el-button>
          </div>

          <!-- 空状态 -->
          <div v-if="filteredLogs.length === 0" class="empty-logs">
            <el-empty description="暂无日志数据">
              <el-button @click="refreshLogs" type="primary">刷新日志</el-button>
            </el-empty>
          </div>

          <!-- 实时连接状态 -->
          <div v-if="realtimeMode" class="realtime-status">
            <el-alert
              :type="wsConnected ? 'success' : 'error'"
              :title="wsConnected ? '实时日志已连接' : '实时日志连接断开'"
              :description="wsConnected ? '正在接收最新日志...' : '尝试重新连接中...'"
              show-icon
              :closable="false"
            />
          </div>
        </div>
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog 
      title="日志详情"
      v-model="logDetailVisible" 
      width="70%"
      :fullscreen="detailFullscreen"
    >
      <template #header>
        <div class="dialog-header">
          <span>日志详情</span>
          <el-button @click="detailFullscreen = !detailFullscreen" type="text" size="small">
            <el-icon><FullScreen v-if="!detailFullscreen" /><Aim v-else /></el-icon>
          </el-button>
        </div>
      </template>

      <div v-if="selectedLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="时间">
            {{ formatLogTime(selectedLog.timestamp, true) }}
          </el-descriptions-item>
          <el-descriptions-item label="级别">
            <el-tag :type="getLevelTagType(selectedLog.level)">
              {{ selectedLog.level.toUpperCase() }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="来源" v-if="selectedLog.source">
            {{ selectedLog.source }}
          </el-descriptions-item>
          <el-descriptions-item label="线程ID" v-if="selectedLog.thread">
            {{ selectedLog.thread }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="log-message-detail">
          <h4>日志消息</h4>
          <pre class="log-message-content">{{ selectedLog.message }}</pre>
        </div>

        <div v-if="selectedLog.stack" class="log-stack-trace">
          <h4>堆栈跟踪</h4>
          <pre class="stack-trace-content">{{ selectedLog.stack }}</pre>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { 
  Document, VideoPlay, VideoPause, Refresh, Delete, Download, Search,
  FullScreen, Aim
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { systemAPI } from '@/utils/api'

// 响应式数据
const loading = ref(false)
const loadingMore = ref(false)
const connecting = ref(false)
const realtimeMode = ref(false)
const wsConnected = ref(false)
const autoScroll = ref(true)
const hasMoreLogs = ref(true)

// 过滤器
const filterLevel = ref('')
const filterSource = ref('')
const searchKeyword = ref('')
const maxLines = ref(1000)
const dateRange = ref([])

// 日志数据
const logs = ref([])
const totalLogs = ref(0)
const currentPage = ref(1)
const pageSize = ref(100)

// 界面状态
const logContainer = ref()
const logDetailVisible = ref(false)
const detailFullscreen = ref(false)
const selectedLog = ref(null)

// WebSocket连接
let ws = null
let reconnectTimer = null

// 计算属性
const filteredLogs = computed(() => {
  let filtered = logs.value

  // 级别过滤
  if (filterLevel.value) {
    filtered = filtered.filter(log => log.level === filterLevel.value)
  }

  // 来源过滤
  if (filterSource.value) {
    filtered = filtered.filter(log => log.source === filterSource.value)
  }

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(log => 
      log.message.toLowerCase().includes(keyword)
    )
  }

  // 时间范围过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const [startTime, endTime] = dateRange.value
    const start = new Date(startTime).getTime()
    const end = new Date(endTime).getTime()
    
    filtered = filtered.filter(log => {
      const logTime = new Date(log.timestamp).getTime()
      return logTime >= start && logTime <= end
    })
  }

  // 限制显示行数
  if (maxLines.value && filtered.length > maxLines.value) {
    filtered = filtered.slice(-maxLines.value)
  }

  return filtered
})

const displayedLogs = computed(() => filteredLogs.value.length)

// 方法
const refreshLogs = async () => {
  try {
    loading.value = true
    const params = {
      page: 1,
      size: pageSize.value,
      level: filterLevel.value,
      source: filterSource.value,
      search: searchKeyword.value,
      start_time: dateRange.value?.[0],
      end_time: dateRange.value?.[1]
    }
    
    const response = await systemAPI.getLogs(params)
    logs.value = response.logs || []
    totalLogs.value = response.total || 0
    currentPage.value = 1
    hasMoreLogs.value = logs.value.length < totalLogs.value
    
    nextTick(() => {
      if (autoScroll.value) {
        scrollToBottom()
      }
    })
  } catch (error) {
    ElMessage.error('加载日志失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const loadMoreLogs = async () => {
  if (!hasMoreLogs.value) return
  
  try {
    loadingMore.value = true
    currentPage.value++
    
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      level: filterLevel.value,
      source: filterSource.value,
      search: searchKeyword.value,
      start_time: dateRange.value?.[0],
      end_time: dateRange.value?.[1]
    }
    
    const response = await systemAPI.getLogs(params)
    const newLogs = response.logs || []
    
    logs.value = [...logs.value, ...newLogs]
    hasMoreLogs.value = logs.value.length < totalLogs.value
    
    nextTick(() => {
      if (autoScroll.value) {
        scrollToBottom()
      }
    })
  } catch (error) {
    ElMessage.error('加载更多日志失败: ' + error.message)
    currentPage.value--
  } finally {
    loadingMore.value = false
  }
}

const toggleRealtime = () => {
  if (realtimeMode.value) {
    stopRealtime()
  } else {
    startRealtime()
  }
}

const startRealtime = async () => {
  try {
    connecting.value = true
    realtimeMode.value = true
    
    // 建立WebSocket连接
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const wsUrl = `${protocol}//${window.location.hostname}:${window.location.port || 8080}/ws/logs`
    
    ws = new WebSocket(wsUrl)
    
    ws.onopen = () => {
      wsConnected.value = true
      connecting.value = false
      ElMessage.success('实时日志连接成功')
    }
    
    ws.onmessage = (event) => {
      try {
        const logData = JSON.parse(event.data)
        
        if (logData.type === 'log') {
          // 添加新日志到列表
          logs.value.push(logData.data)
          totalLogs.value++
          
          // 限制内存中的日志数量
          if (logs.value.length > maxLines.value * 2) {
            logs.value = logs.value.slice(-maxLines.value)
          }
          
          nextTick(() => {
            if (autoScroll.value) {
              scrollToBottom()
            }
          })
        }
      } catch (error) {
        console.error('解析实时日志消息失败:', error)
      }
    }
    
    ws.onclose = () => {
      wsConnected.value = false
      if (realtimeMode.value) {
        // 自动重连
        reconnectTimer = setTimeout(startRealtime, 5000)
      }
    }
    
    ws.onerror = (error) => {
      console.error('实时日志WebSocket连接错误:', error)
      wsConnected.value = false
      connecting.value = false
      ElMessage.error('实时日志连接失败')
    }
  } catch (error) {
    connecting.value = false
    ElMessage.error('启动实时日志失败: ' + error.message)
  }
}

const stopRealtime = () => {
  realtimeMode.value = false
  
  if (reconnectTimer) {
    clearTimeout(reconnectTimer)
    reconnectTimer = null
  }
  
  if (ws) {
    ws.close()
    ws = null
  }
  
  wsConnected.value = false
  ElMessage.info('实时日志已停止')
}

const clearLogs = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有日志吗？此操作不可恢复。',
      '清空日志',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 清空前端显示的日志
    logs.value = []
    totalLogs.value = 0
    
    // 发送清空日志的API请求（如果后端支持）
    // await systemAPI.clearLogs()
    
    ElMessage.success('日志已清空')
  } catch {
    // 用户取消
  }
}

const downloadLogs = () => {
  try {
    const logContent = filteredLogs.value
      .map(log => `${formatLogTime(log.timestamp, true)} [${log.level.toUpperCase()}] ${log.source ? `[${log.source}] ` : ''}${log.message}`)
      .join('\n')
    
    const blob = new Blob([logContent], { type: 'text/plain;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    
    const a = document.createElement('a')
    a.href = url
    a.download = `ems-logs-${new Date().toISOString().slice(0, 10)}.log`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    
    ElMessage.success('日志导出成功')
  } catch (error) {
    ElMessage.error('导出日志失败: ' + error.message)
  }
}

const applyFilters = () => {
  if (!realtimeMode.value) {
    refreshLogs()
  }
}

const handleScroll = (event) => {
  const { scrollTop, scrollHeight, clientHeight } = event.target
  const isAtBottom = scrollTop + clientHeight >= scrollHeight - 10
  
  if (!isAtBottom && autoScroll.value) {
    autoScroll.value = false
  }
}

const handleAutoScrollChange = (value) => {
  if (value) {
    nextTick(() => {
      scrollToBottom()
    })
  }
}

const scrollToBottom = () => {
  if (logContainer.value) {
    logContainer.value.scrollTop = logContainer.value.scrollHeight
  }
}

const showLogDetail = (log) => {
  selectedLog.value = log
  logDetailVisible.value = true
}

// 工具函数
const formatLogTime = (timestamp, detailed = false) => {
  const date = new Date(timestamp)
  if (detailed) {
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      fractionalSecondDigits: 3
    })
  } else {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }
}

const getLevelTagType = (level) => {
  const types = {
    debug: 'info',
    info: 'success',
    warn: 'warning',
    error: 'danger'
  }
  return types[level] || 'info'
}

const getLogClass = (log) => {
  return {
    'log-debug': log.level === 'debug',
    'log-info': log.level === 'info',
    'log-warn': log.level === 'warn',
    'log-error': log.level === 'error'
  }
}

const highlightMessage = (message) => {
  if (!searchKeyword.value) return message
  
  const keyword = searchKeyword.value
  const regex = new RegExp(`(${keyword})`, 'gi')
  return message.replace(regex, '<mark>$1</mark>')
}

// 生命周期
onMounted(() => {
  refreshLogs()
})

onUnmounted(() => {
  stopRealtime()
})
</script>

<style scoped>
.logs-viewer {
  max-width: 1200px;
  margin: 0 auto;
}

.logs-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.header-actions {
  margin-left: auto;
  display: flex;
  gap: 12px;
}

.log-filters {
  margin-bottom: 20px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.log-stats {
  font-size: 12px;
  color: #8c8c8c;
  line-height: 32px;
  text-align: right;
}

.log-content {
  height: 600px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  overflow: hidden;
}

.log-container {
  height: 100%;
  overflow-y: auto;
  padding: 8px;
  background: #000;
  color: #fff;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.4;
}

.log-entry {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  padding: 2px 0;
  cursor: pointer;
  word-wrap: break-word;
  transition: background-color 0.2s;
}

.log-entry:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.log-time {
  flex-shrink: 0;
  color: #8c8c8c;
  font-weight: 500;
}

.log-level {
  flex-shrink: 0;
}

.log-source {
  flex-shrink: 0;
}

.log-message {
  flex: 1;
  word-break: break-all;
}

.log-message :deep(mark) {
  background: #fadb14;
  color: #000;
  padding: 1px 2px;
  border-radius: 2px;
}

.log-debug {
  opacity: 0.8;
}

.log-debug .log-message {
  color: #8c8c8c;
}

.log-info .log-message {
  color: #fff;
}

.log-warn .log-message {
  color: #faad14;
}

.log-error .log-message {
  color: #ff4d4f;
  font-weight: 500;
}

.load-more {
  text-align: center;
  padding: 20px;
  background: rgba(255, 255, 255, 0.05);
}

.empty-logs {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.realtime-status {
  position: sticky;
  bottom: 0;
  padding: 8px;
  background: rgba(0, 0, 0, 0.9);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.log-detail {
  color: #262626;
}

.log-message-detail {
  margin-top: 20px;
}

.log-message-detail h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
}

.log-message-content {
  background: #f8f8f8;
  padding: 12px;
  border-radius: 4px;
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.6;
}

.log-stack-trace {
  margin-top: 20px;
}

.log-stack-trace h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
}

.stack-trace-content {
  background: #f8f8f8;
  padding: 12px;
  border-radius: 4px;
  margin: 0;
  white-space: pre-wrap;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 11px;
  line-height: 1.5;
  color: #d9534f;
}

/* 滚动条样式 */
.log-container::-webkit-scrollbar {
  width: 8px;
}

.log-container::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
}

.log-container::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

.log-container::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .logs-viewer {
    margin: 0 10px;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .header-actions .el-button,
  .header-actions .el-button-group {
    width: 100%;
  }
  
  .log-content {
    height: 400px;
  }
  
  .log-entry {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .log-time,
  .log-level,
  .log-source {
    flex-shrink: 1;
  }
  
  .log-stats {
    text-align: left;
  }
}

@media (max-width: 576px) {
  .log-filters .el-col {
    margin-bottom: 12px;
  }
  
  .log-container {
    font-size: 11px;
  }
}
</style>